<?php
/**
 * 汇友科技
 * @copyright (c) 2017 http://www.huiyou365.net All rights reserved.
 * @author: Creatint <creatint@163.com>
 */

namespace Admin\Model;

use Think\Model;
use Think\Page;

class ConfigModel extends Model{

    protected $_validate = array(
        array('name', 'require', '标识不能为空', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
        array('name', '', '标识已经存在', self::EXISTS_VALIDATE, 'unique', self::MODEL_BOTH),
        array('title', 'require', '名称不能为空', self::EXISTS_VALIDATE , 'regex', self::MODEL_BOTH),
    );

    protected $_auto = array(
        array('create_time', NOW_TIME, self::MODEL_INSERT),
        array('update_time', NOW_TIME, self::MODEL_BOTH),
    );

    protected $page = null;

    /**
     * 获取配置列表，原生数据.
     *
     * @return mixed
     */
    public function get($query = null, $field = true, $order = 'sort ASC', $showPage = true){
        $map = array();

        $query['id']>0 && $map['id'] = $query['id'];
        unset($query['id']);
        foreach($query as $k=>$v){
            $map[$k] = $v;
        }

        if ( $map['id']>0 ) {
            $res = $this
                ->where($map)
                ->field($field)
                ->find();
        } else {
            if ( $showPage ) {
                $res = $this
                    ->where($map)
                    ->order($order)
                    ->page(I('get.p',0) . ',' . C('LIST_ROWS_BACK'))
                    ->field($field)
                    ->select();
                $count = $this->where($map)->count();
                $this->page = show_page(new Page($count, C('LIST_ROWS_BACK')));
            } else {
                $res = $this
                    ->where($map)
                    ->order($order)
                    ->field($field)
                    ->select();
            }
        }


        return $res;
    }

    /**
     * 添加配置项.
     *
     * @param $data
     * @return bool
     */
    public function update($data){

        // 无status则默认为1
        $data['status'] != 1 && $data['status'] != 0 && $data['status'] = 1;

        // 若有id，取数据库中数据，相同值的字段销毁
        if ( $data['id']>0 ) {
            $info = $this->find($data['id']);
            foreach( $data as $k=>$v ) {
                if ( isset($info[$k]) && $info[$k] == $v && $k != 'id') {
                    unset($data[$k]);
                }
            }
        }

        // name字段大写
        isset($data['name']) && $data['name'] = strtoupper($data['name']);

        // 程序出口值,0:失败, >1:成功, 以位运算的或运算来修改其值
        $res = 1;

        // 验证数据,验证失败则 res = 0
        $res &= (bool)($data = $this->create($data)) ;

        // 如果id存在,则更新,保存失败则 res = 0
        $res && $data['id'] && ($res &= (bool)$this->save($data));

        // 如果id不存在,则新增,新增成功则 res = id（返回ID）
        $res && !$data['id'] && ($id = $this->add($data)) && ($res = $id);

        // 程序出口
        return $res;
    }


    public function remove($id){
        if ( !$id ) {
            $this->error = '待删除项为空';
            return false;
        }
        $map = [
            'id'=>[
                'IN',
                $id
            ]
        ];
        if ( $this->where($map)->delete() ) {
            S('DB_CONFIG', null);
            return true;
        } else {
            return false;
        }
    }

    public function getPage(){
        return $this->page;
    }

}